/*
 * @Description: enter your description
 * @Autor: bxs
 * @Date: 2021-12-16 13:57:44
 * @LastEditors: bxs
 * @LastEditTime: 2021-12-18 16:39:20
 */
/**
 * 函数柯里化 ES6
 * @param {function} fn   待柯里化函数
 * @param  {...any} rest1 携带参数
 * @returns 柯里化后函数
 */
export function currying(fn, ...rest1) {
    // 调用柯里化后的函数的参数
    return function(...rest2) {
      return fn.apply(null, rest1.concat(rest2))
    }
}

/**
 * 获取输入的类型
 * @param {any} param 
 * @returns 
 */
export function getClass(param) { //判断数据类型
  return Object.prototype.toString.call(param).slice(8, -1);
}

/**
 * 获取剩余参数
 * @param {arguments} argment 
 * @param {Number} startIndex 
 * @returns 
 */
export function getArgs(args, startIndex) {
	let argArr = []
	if (args.length > startIndex) {
		for (let index = startIndex; index < args.length; index++){
			argArr.push(args[index])	
		}
	}
	return argArr
}

/**
 * 防抖函数
 * @param {Function} fn 
 * @param {Number} delay 
 * @returns 
 */
export function debounce(func, delay){
    let timer = null //借助闭包
    return function() {
        if(timer){
            clearTimeout(timer) 
        }
        timer = setTimeout(func,delay) // 简化写法
    }
}

/**
 * 节流函数,
 * options.begin === true第一次触发事件就立刻会执行回调函数
 * options.end === true事件停止触发后也会执行一次该回调函数
 * @param {Function} func 
 * @param {Number} wait 
 * @param {Object} options 
 * @returns 
 */
export function throttle(func, wait, options = {}) {
	let timeout,
	  previous = 0
  
	return function() {
	  let now = +new Date()
	  let remain = wait - (now - previous)
  
	  if (remain < 0) {
		if (previous === 0 && !options.begin) {
		  previous = now
		  return
		}
  
		if (timeout) {
		  clearTimeout(timeout)
		  timeout = null
		}
  
		previous = now
		func.call(this, arguments)
	  } else if (!timeout && options.end) {
		timeout = setTimeout(() => {
		  func.call(this, arguments)
		  timeout = null
		}, wait)
	  }
	}
  }
